<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { updateUser, getUserInfo } from '@/api/user'
import { uploadFile } from '@/api/common'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const formData = reactive({
  id: '',
  username: '',
  oldPassword: '',
  newPassword: '',
  email: '',
  avatar: ''
})

// 表单验证规则
const rules = {
  username: [
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  oldPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200) {
      formData.id = res.data.id
      formData.username = res.data.username
      formData.email = res.data.email
      formData.avatar = res.data.avatar
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const formRef = ref(null)

// 头像上传相关
const handleCustomUpload = async (option) => {
  try {
    const res = await uploadFile(option.file)
    if (res.code === 200) {
      formData.avatar = res.data
      option.onSuccess(res, option.file)
      ElMessage.success('头像上传成功')
    } else {
      option.onError(res.message || '上传失败')
    }
  } catch (err) {
    option.onError(err)
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建更新数据，只包含有值的字段
        const updateData = {}
        if (formData.username) updateData.username = formData.username
        if (formData.oldPassword && formData.newPassword) {
          updateData.oldPassword = formData.oldPassword
          updateData.newPassword = formData.newPassword
        }
        if (formData.email) updateData.email = formData.email
        if (formData.avatar) updateData.avatar = formData.avatar
        updateData.id = formData.id

        const response = await updateUser(updateData)
        if (response.code === 200) {
          // 更新成功后，更新 store 中的用户信息
          userStore.setUserInfo({
            ...userStore.userInfo,
            ...updateData
          })
          ElMessage.success('更新成功')
          router.push('/profile')
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } catch (error) {
        ElMessage.error('更新失败，请稍后重试')
      }
    }
  })
}

// 取消更新
const handleCancel = () => {
  router.push('/profile')
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="user-update-container">
    <div class="update-form">
      <div class="form-header">
        <h2>更新用户信息</h2>
        <el-button @click="handleCancel">返回个人中心</el-button>
      </div>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="formData.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="formData.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :http-request="handleCustomUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="avatar-tip">支持 jpg、png 格式，大小不超过 2MB</div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.user-update-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.update-form {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.update-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form {
  max-width: 500px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.form-header h2 {
  margin: 0;
}

.avatar-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style> 